import request from '@/axios'
import { check, checkResultPage, Page, ResultPage } from "./baseModel"

export interface OrderSearch {
    id: string | undefined
    userId: string | undefined
    status: number | undefined
    dateRange: string[]
}

export interface OrderAddress {
    name: string
    phone: string
    address: string
}

export interface OrderRider {
    id: string
    name: string
    phone: string
}

export interface OrderProduct {
    id: string
    name: string
    description: string
    image: string
    currentPrice: number
    originalPrice: number
    count: number
}

export interface OrderUser {
    id: string
    username: string
    phone: string
    image: string
}

export interface Order {
    id: string
    orderTime: string
    finalPrice: number
    status: string
    deliveryTime: string,

    user: OrderUser                         // 下单用户
    address: OrderAddress                   // 收件地址
    rider: OrderRider | undefined           // 配送骑手
    products: OrderProduct[]                // 商品列表
}

export const orderStatus = [
    { label: '待支付', value: 0, type: 'info' },
    { label: '待发货', value: 1, type: 'warning' },
    { label: '配送中', value: 2, type: 'primary' },
    { label: '已完成', value: 3, type: 'primary' }
]

export function getInitOrderSearch() {
    return {
        id: undefined,
        userId: undefined,
        status: undefined,
        dateRange: []
    }
}

/**
 * 用于发起商品请求的 API
 *  static pagingSearch(search, page)       分页获取数据
 *  static delivery(from)                   发送订单
 */
export class OrderApi {

    static baseUrl = "/order"

    // 分页获取数据
    static async pagingSearch(search: OrderSearch, page: Page): Promise<ResultPage<Order>> {
        try {
            const response = await request.get(
                `${this.baseUrl}/search`,
                { params: { ...search, ...page }, data: { loading: '加载商品数据' } }
            )
            return checkResultPage(response) as ResultPage<Order>
        }
        catch (error: any) { throw error }
    }

    // 发送订单
    static async delivery(form: any) {
        try {
            const response = await request.get(
                this.baseUrl + "/delivery", 
                {params: form, data: {loading: '发货中'}}
            )
            check(response)
        } 
        catch (error: any) { throw error }
    }

    // 取消订单
    static async cancel(id: string) {
        try {
            const response = await request.get(
                this.baseUrl + "/cancel?id=" + id
            )
            check(response)
        } 
        catch (error: any) { throw error }
    }

    // 确认送达
    static async complete(id: string) {
        try {
            const response = await request.get(
                this.baseUrl + "/complete?id=" + id
            )
            check(response)
        } 
        catch (error: any) { throw error }
    }
}